package handler

import (
	"encoding/json"
	"strconv"
	"time"
	"weibo-biz/cache"
	"weibo-biz/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func AddDetail(c *gin.Context) {
	name := c.PostForm("name")
	price := c.PostForm("price")
	num := c.PostForm("num")
	info := c.PostForm("info")
	data := models.Wei{
		Model: gorm.Model{},
		Name:  name,
		Price: price,
		Num:   num,
		Info:  info,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "fall",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "okm",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var wei models.Wei
	redis_key := "list_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&wei)
		jsonData, _ := json.Marshal(wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "okm",
		"data": wei,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var wei []models.Wei
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&wei)
		jsonData, _ := json.Marshal(wei)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &wei)
	}
	var total int64
	models.DB.Model(&models.Wei{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "okm",
		"data":  wei,
		"total": total,
	})
	return
}
